package com.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.reggie.Exception.DishStatusException;
import com.reggie.dao.DishDao;
import com.reggie.dao.SetmealDao;
import com.reggie.dao.SetmealDishDao;
import com.reggie.pojo.Dish;
import com.reggie.pojo.Setmeal;
import com.reggie.pojo.SetmealDish;
import com.reggie.service.SetMealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class SetMealServiceImpl implements SetMealService {
    @Autowired
    private SetmealDao setMealDao;
    @Autowired
    private SetmealDishDao setmealDishDao;
    @Autowired
    private DishDao dishDao;

    @Override
    public Page<Setmeal> selectByPage(Integer page, Integer pageSize, String name) {
        Page<Setmeal> page_setmeal = new Page<>(page, pageSize);
        LambdaQueryWrapper<Setmeal> lqw = new LambdaQueryWrapper();
        lqw.like(StringUtils.isNotEmpty(name), Setmeal::getName, name);
        setMealDao.selectPage(page_setmeal, lqw);
        return page_setmeal;
    }

    @Override
    @Transactional
    public void addSetMeal(Setmeal setmeal) {
        setMealDao.insert(setmeal);
    }

    @Override
    public boolean updateStatusById(Integer status, Long... ids) {
        //ids表示要修改的套餐，得到套餐中的每一个菜品，看看每个菜品的状态是啥样的
        for (Long id : ids) {
            if (id != null) {
                List<SetmealDish> setmealDishes = setmealDishDao.selectBySetmealId(id);
                setmealDishes.forEach((item) -> {
                    Dish dish = dishDao.selectById(item.getDishId());
                    System.out.println(dish);
                    if(dish.getStatus() == 0){
                        throw new DishStatusException("您要启用的这个套餐中包含已经下架的菜品！请先启用该菜品");
                    }else {
                        setMealDao.updateStatusById(status, id);
                    }
                });
            }
        }
        return true;
    }

    @Override
    public void deleteById(Long... ids) {
        for (Long id : ids) {
            setMealDao.deleteById(id);
        }
    }

    @Override
    public Setmeal selectById(Long id) {
        return setMealDao.selectById(id);
    }

    @Override
    public void updateSetmeal(Setmeal setmeal) {
        //只修改传输过来的那一天记录即可
        LambdaQueryWrapper<Setmeal> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Setmeal::getId,setmeal.getId());
        setMealDao.update(setmeal,lqw);
    }

    @Override
    public List<Setmeal> selectSetmealByCategoryId(Long id,Integer status) {
        List<Setmeal> setmeals = setMealDao.selectByCategoryId(id, status);
        return setmeals;
    }
}
